package com.xjiye_test.payServer.servletGroup.weixin;

import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.db.Page;
import com.xiaoleilu.hutool.db.PageResult;
import com.xjiye_test.payServer.dao.OrderDao;
import com.xjiye_test.payServer.pojo.PayRecord;
import com.xjiye_test.payServer.serverletUtil.IdWorker;
import com.xjiye_test.payServer.serverletUtil.ReadBytes;
import com.xjiye_test.payServer.serverletUtil.Signature;
import com.xjiye_test.payServer.serverletUtil.XMLParser;
import org.xml.sax.SAXException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

public class WexinRefund extends HttpServlet {
    protected synchronized void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String reStr=null;
        req.setCharacterEncoding("UTF-8");
        int size = req.getContentLength();
        InputStream is = req.getInputStream();
        Map mapRequest = null;
        try {
            mapRequest = XMLParser.getMapFromXML(new String(ReadBytes.readBytes(is, size)));
            OrderDao orderdao=new OrderDao();
            List<String> keys= new ArrayList<>();
            List<String> values= new ArrayList<>();
            keys.add("suppOrderNo=");
            values.add(mapRequest.get("out_trade_no").toString());
            keys.add("suppId=");
            values.add(mapRequest.get("mch_id").toString());
            PageResult<Entity> orders=orderdao.getDataByCondition(new Page(0,10),keys,values);
            if(orders.size()==0){
                reStr="<xml>\n" +
                        "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                        "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                        "   <result_code><![CDATA[FAIL]]></result_code>\n" +
                        "   <err_code><![CDATA[SYSTEMERROR]]></err_code>\n" +
                        "   <err_code_des><![CDATA[订单不存在]]></err_code_des>\n" +
                        "</xml>";
            }
            if(orders.size()==1){
                //构造退款订单对象
                String refundId= IdWorker.getIdWorker().nextId()+"";
                PayRecord pay=new PayRecord();
                pay.setTime(new Date());
                pay.setAppid(mapRequest.get("appid").toString());
                pay.setSuppId(mapRequest.get("mch_id").toString());
                pay.setWechatOrderNo(orders.get(0).getStr("wechatOrderNo"));
                pay.setSuppOrderNo(mapRequest.get("out_trade_no").toString());
                pay.setOpenid(orders.get(0).getStr("openid"));
                pay.setPaytype(orders.get(0).getStr("paytype"));
                pay.setPaystatus("REFUND");
                pay.setAmount(0);
                pay.setWechatRefundNo(refundId);
                pay.setSuppRefundNo(mapRequest.get("out_refund_no").toString());
                pay.setRefundAmount(Integer.parseInt(mapRequest.get("total_fee").toString()));
                pay.setFee(0);
                pay.setFeeAmount(0);
                orderdao.addOrderInfo(pay);
                reStr= Signature.getSignFromResponseString("<xml>\n" +
                        "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                        "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                        "   <appid><![CDATA["+mapRequest.get("appid")+"]]></appid>\n" +
                        "   <mch_id><![CDATA["+mapRequest.get("mch_id")+"]]></mch_id>\n" +
                        "   <nonce_str><![CDATA[NfsMFbUFpdbEhPXP]]></nonce_str>\n" +
                        "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                        "   <transaction_id><![CDATA["+orders.get(0).getStr("wechatOrderNo")+"]]></transaction_id>\n" +
                        "   <out_trade_no><![CDATA["+orders.get(0).getStr("suppOrderNo")+"]]></out_trade_no>\n" +
                        "   <out_refund_no><![CDATA["+mapRequest.get("out_refund_no")+"]]></out_refund_no>\n" +
                        "   <refund_id><![CDATA["+refundId+"]]></refund_id>\n" +
                        "   <refund_channel><![CDATA[]]></refund_channel>\n" +
                        "   <refund_fee>"+orders.get(0).getStr("amount")+"</refund_fee> \n" +
                        "</xml>","123456");
            }
            if(orders.size()==2){
                reStr="<xml>\n" +
                        "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                        "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                        "   <result_code><![CDATA[FAIL]]></result_code>\n" +
                        "   <err_code><![CDATA[SYSTEMERROR]]></err_code>\n" +
                        "   <err_code_des><![CDATA[订单已经退款]]></err_code_des>\n" +
                        "</xml>";
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            out.println(reStr);
            out.flush();
        }

    }
}
